package One;
import java.awt.*;
import java.net.*;
import java.util.StringTokenizer;

public class Server implements Runnable{

    User u1;
    User u2;

    public Server(User u1, User u2) {
        this.u1 = u1;
        this.u2 = u2;
    }

    @Override
    public void run() {
        // 接收数据
        DatagramPacket pack = null;
        DatagramSocket mail = null;
        byte b[] = new byte[8192];
        try
        {
            pack = new DatagramPacket(b,b.length);
            mail = new DatagramSocket(2000);
            while(true)//循环接收数据
            {
                mail.receive(pack);
                String message = new String(pack.getData(),0,pack.getLength());
                b = message.trim().getBytes();
                //通过接收的信息获取发送者的用户名
                StringTokenizer s = new StringTokenizer(message,":");
                String sender = s.nextToken();
                //发送数据
                if(sender.equals(u1.userName)){//如果用户1是发送者，则将信息发送给用户2
                    DatagramPacket dataPack = new DatagramPacket(b,b.length,u2.getSrcAddr(),u2.getSrc());
                    DatagramSocket send = new DatagramSocket();
                    send.send(dataPack);
                    send.close();
                }else {//如果用户2是发送者，则将信息发送给用户1
                    DatagramPacket dataPack = new DatagramPacket(b,b.length,u1.getSrcAddr(),u1.getSrc());
                    DatagramSocket send = new DatagramSocket();
                    send.send(dataPack);
                    send.close();
                }
            }
        }
        catch(Exception e){}
    }

    public static void main(String[] args) {

        Font font = new Font("楷体",0,26);//创建字体对象
        User.InitGlobalFont(font);//将默认字体设置为全局字体
        try {
            //创建客户端
            User user1 = new User("用户2","用户1", InetAddress.getByName("localhost"),2453);
            User user2 = new User("用户1","用户2", InetAddress.getByName("localhost"),2345);
            //设置窗口位置和大小
            user1.setBounds(100,100,600,500);
            user2.setBounds(800,100,600,500);
            //创建服务端
            Server server = new Server(user1,user2);
            //创建线程并启动
            Thread thread = new Thread(server);
            thread.start();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }
}
